from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.http import JsonResponse
from django.db.models import Q, Sum
from .models import (
    SparePart, SparePartCategory, Supplier, 
    InventoryRecord, UsageRecord, PurchaseOrder, PurchaseOrderItem
)
from tickets.models import Ticket

@login_required
def inventory_list(request):
    """备件库存列表"""
    # 搜索和过滤
    search_query = request.GET.get('q', '')
    category_id = request.GET.get('category', '')
    status_filter = request.GET.get('status', '')
    
    spare_parts = SparePart.objects.all()
    
    if search_query:
        spare_parts = spare_parts.filter(
            Q(name__icontains=search_query) |
            Q(part_number__icontains=search_query) |
            Q(model__icontains=search_query)
        )
    
    if category_id:
        spare_parts = spare_parts.filter(category_id=category_id)
    
    if status_filter:
        if status_filter == 'low':
            spare_parts = [p for p in spare_parts if p.is_low_stock()]
        elif status_filter == 'high':
            spare_parts = [p for p in spare_parts if p.is_over_stock()]
    
    categories = SparePartCategory.objects.all()
    
    return render(request, 'spare_parts/inventory_list.html', {
        'spare_parts': spare_parts,
        'categories': categories,
        'search_query': search_query,
        'selected_category': category_id,
        'selected_status': status_filter,
    })

@login_required
def inventory_detail(request, pk):
    """备件库存详情"""
    spare_part = get_object_or_404(SparePart, pk=pk)
    inventory_records = spare_part.inventory_records.all().order_by('-operation_date')[:20]
    usage_records = spare_part.usage_records.all().order_by('-used_at')[:10]
    
    return render(request, 'spare_parts/inventory_detail.html', {
        'spare_part': spare_part,
        'inventory_records': inventory_records,
        'usage_records': usage_records,
    })

@login_required
def inventory_add(request):
    """添加库存（入库操作）"""
    if request.method == 'POST':
        spare_part_id = request.POST.get('spare_part')
        quantity = request.POST.get('quantity')
        notes = request.POST.get('notes', '')
        
        try:
            spare_part = SparePart.objects.get(pk=spare_part_id)
            quantity = int(quantity)
            
            if quantity <= 0:
                messages.error(request, '入库数量必须大于0')
                return redirect('spare_parts:inventory_add')
            
            # 创建入库记录
            InventoryRecord.objects.create(
                spare_part=spare_part,
                operation_type='in',
                quantity=quantity,
                operator=request.user,
                notes=notes
            )
            
            messages.success(request, f'成功入库 {quantity} 个 {spare_part.name}')
            return redirect('spare_parts:inventory_list')
            
        except (SparePart.DoesNotExist, ValueError):
            messages.error(request, '无效的备件或数量')
    
    spare_parts = SparePart.objects.filter(status='active')
    return render(request, 'spare_parts/inventory_add.html', {
        'spare_parts': spare_parts,
    })

@login_required
def usage_list(request):
    """使用记录列表"""
    usage_records = UsageRecord.objects.select_related('spare_part', 'used_by', 'ticket').order_by('-used_at')
    
    # 搜索过滤
    search_query = request.GET.get('q', '')
    if search_query:
        usage_records = usage_records.filter(
            Q(spare_part__name__icontains=search_query) |
            Q(spare_part__part_number__icontains=search_query) |
            Q(used_by__username__icontains=search_query) |
            Q(ticket__title__icontains=search_query)
        )
    
    return render(request, 'spare_parts/usage_list.html', {
        'usage_records': usage_records,
        'search_query': search_query,
    })

@login_required
def usage_add(request):
    """添加使用记录"""
    if request.method == 'POST':
        spare_part_id = request.POST.get('spare_part')
        quantity = request.POST.get('quantity')
        purpose = request.POST.get('purpose', '')
        ticket_id = request.POST.get('ticket', '')
        
        try:
            spare_part = SparePart.objects.get(pk=spare_part_id)
            quantity = int(quantity)
            
            if quantity <= 0:
                messages.error(request, '使用数量必须大于0')
                return redirect('spare_parts:usage_add')
            
            if quantity > spare_part.current_stock:
                messages.error(request, f'库存不足，当前库存：{spare_part.current_stock}')
                return redirect('spare_parts:usage_add')
            
            ticket = None
            if ticket_id:
                ticket = Ticket.objects.get(pk=ticket_id)
            
            # 创建使用记录
            usage_record = UsageRecord.objects.create(
                spare_part=spare_part,
                quantity=quantity,
                used_by=request.user,
                purpose=purpose,
                ticket=ticket
            )
            
            # 创建出库记录
            InventoryRecord.objects.create(
                spare_part=spare_part,
                operation_type='out',
                quantity=quantity,
                operator=request.user,
                related_usage=usage_record,
                notes=f'使用记录：{purpose}'
            )
            
            messages.success(request, f'成功记录使用 {quantity} 个 {spare_part.name}')
            return redirect('spare_parts:usage_list')
            
        except (SparePart.DoesNotExist, Ticket.DoesNotExist, ValueError):
            messages.error(request, '无效的备件、工单或数量')
    
    spare_parts = SparePart.objects.filter(status='active')
    tickets = Ticket.objects.filter(status__in=['repairing', 'testing', 'quality_check'])
    
    return render(request, 'spare_parts/usage_add.html', {
        'spare_parts': spare_parts,
        'tickets': tickets,
    })

@login_required
def purchase_list(request):
    """采购订单列表"""
    purchase_orders = PurchaseOrder.objects.select_related('supplier', 'requested_by').order_by('-created_at')
    
    # 状态过滤
    status_filter = request.GET.get('status', '')
    if status_filter:
        purchase_orders = purchase_orders.filter(status=status_filter)
    
    return render(request, 'spare_parts/purchase_list.html', {
        'purchase_orders': purchase_orders,
        'selected_status': status_filter,
    })

@login_required
def purchase_detail(request, pk):
    """采购订单详情"""
    purchase_order = get_object_or_404(PurchaseOrder.objects.select_related('supplier', 'requested_by', 'approved_by'), pk=pk)
    order_items = purchase_order.order_items.select_related('spare_part')
    
    return render(request, 'spare_parts/purchase_detail.html', {
        'purchase_order': purchase_order,
        'order_items': order_items,
    })

@login_required
def supplier_list(request):
    """供应商列表"""
    suppliers = Supplier.objects.all().order_by('name')
    return render(request, 'spare_parts/supplier_list.html', {
        'suppliers': suppliers,
    })

@login_required
def category_list(request):
    """分类列表"""
    categories = SparePartCategory.objects.all().order_by('name')
    return render(request, 'spare_parts/category_list.html', {
        'categories': categories,
    })

@login_required
def sku_management(request):
    """SKU管理"""
    from django.core.paginator import Paginator
    
    # 获取所有过滤参数
    sku_query = request.GET.get('sku', '')
    name_query = request.GET.get('name', '')
    category_id = request.GET.get('category', '')
    status_filter = request.GET.get('status', '')
    stock_status_filter = request.GET.get('stock_status', '')
    
    # 基础查询
    spare_parts = SparePart.objects.select_related('category', 'supplier').all()
    
    # 应用过滤条件
    if sku_query:
        spare_parts = spare_parts.filter(part_number__icontains=sku_query)
    
    if name_query:
        spare_parts = spare_parts.filter(name__icontains=name_query)
    
    if category_id:
        spare_parts = spare_parts.filter(category_id=category_id)
    
    if status_filter:
        spare_parts = spare_parts.filter(status=status_filter)
    
    if stock_status_filter:
        if stock_status_filter == 'low':
            spare_parts = [p for p in spare_parts if p.is_low_stock()]
        elif stock_status_filter == 'high':
            spare_parts = [p for p in spare_parts if p.is_over_stock()]
        elif stock_status_filter == 'normal':
            spare_parts = [p for p in spare_parts if not p.is_low_stock() and not p.is_over_stock()]
    
    # 分页
    paginator = Paginator(spare_parts, 20)  # 每页20条
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    # 统计信息
    total_count = SparePart.objects.count()
    active_count = SparePart.objects.filter(status='active').count()
    low_stock_count = len([p for p in SparePart.objects.all() if p.is_low_stock()])
    over_stock_count = len([p for p in SparePart.objects.all() if p.is_over_stock()])
    
    categories = SparePartCategory.objects.all()
    
    return render(request, 'spare_parts/sku_management.html', {
        'spare_parts': page_obj,
        'page_obj': page_obj,
        'is_paginated': paginator.num_pages > 1,
        'categories': categories,
        'total_count': total_count,
        'active_count': active_count,
        'low_stock_count': low_stock_count,
        'over_stock_count': over_stock_count,
    })

@login_required
def sku_add(request):
    """添加SKU"""
    if request.method == 'POST':
        try:
            # 获取表单数据
            name = request.POST.get('name')
            model = request.POST.get('model')
            part_number = request.POST.get('part_number')
            category_id = request.POST.get('category')
            supplier_id = request.POST.get('supplier')
            supplier_part_number = request.POST.get('supplier_part_number')
            unit = request.POST.get('unit')
            unit_price = request.POST.get('unit_price')
            status = request.POST.get('status')
            min_stock = request.POST.get('min_stock', 0)
            max_stock = request.POST.get('max_stock', 0)
            initial_stock = request.POST.get('initial_stock', 0)
            specifications = request.POST.get('specifications', '')
            notes = request.POST.get('notes', '')
            
            # 验证必填字段
            if not all([name, model, part_number, category_id, unit, unit_price, status]):
                messages.error(request, '请填写所有必填字段')
                return redirect('spare_parts:sku_add')
            
            # 检查SKU编号是否已存在
            if SparePart.objects.filter(part_number=part_number).exists():
                messages.error(request, f'SKU编号 "{part_number}" 已存在')
                return redirect('spare_parts:sku_add')
            
            # 获取分类和供应商对象
            category = SparePartCategory.objects.get(id=category_id)
            supplier = None
            if supplier_id:
                supplier = Supplier.objects.get(id=supplier_id)
            
            # 创建备件
            spare_part = SparePart.objects.create(
                name=name,
                model=model,
                part_number=part_number,
                category=category,
                supplier=supplier,
                supplier_part_number=supplier_part_number,
                unit=unit,
                unit_price=unit_price,
                status=status,
                min_stock=min_stock,
                max_stock=max_stock,
                specifications=specifications,
                notes=notes
            )
            
            # 如果有初始库存，创建入库记录
            initial_stock = int(initial_stock)
            if initial_stock > 0:
                InventoryRecord.objects.create(
                    spare_part=spare_part,
                    operation_type='in',
                    quantity=initial_stock,
                    operator=request.user,
                    notes=f'初始库存 {initial_stock} {spare_part.unit}'
                )
            
            messages.success(request, f'成功创建备件: {spare_part.name}')
            return redirect('spare_parts:sku_management')
            
        except (SparePartCategory.DoesNotExist, Supplier.DoesNotExist, ValueError) as e:
            messages.error(request, '数据验证失败，请检查输入')
        except Exception as e:
            messages.error(request, f'创建备件时发生错误: {str(e)}')
    
    # GET请求显示表单
    categories = SparePartCategory.objects.all()
    suppliers = Supplier.objects.all()
    
    return render(request, 'spare_parts/sku_add.html', {
        'categories': categories,
        'suppliers': suppliers,
    })

@login_required
def sku_edit(request, pk):
    """编辑SKU"""
    spare_part = get_object_or_404(SparePart, pk=pk)
    
    if request.method == 'POST':
        try:
            # 获取表单数据
            name = request.POST.get('name')
            model = request.POST.get('model')
            category_id = request.POST.get('category')
            supplier_id = request.POST.get('supplier')
            supplier_part_number = request.POST.get('supplier_part_number')
            unit = request.POST.get('unit')
            unit_price = request.POST.get('unit_price')
            status = request.POST.get('status')
            min_stock = request.POST.get('min_stock', 0)
            max_stock = request.POST.get('max_stock', 0)
            specifications = request.POST.get('specifications', '')
            notes = request.POST.get('notes', '')
            
            # 验证必填字段
            if not all([name, model, category_id, unit, unit_price, status]):
                messages.error(request, '请填写所有必填字段')
                return redirect('spare_parts:sku_edit', pk=pk)
            
            # 获取分类和供应商对象
            category = SparePartCategory.objects.get(id=category_id)
            supplier = None
            if supplier_id:
                supplier = Supplier.objects.get(id=supplier_id)
            
            # 更新备件信息
            spare_part.name = name
            spare_part.model = model
            spare_part.category = category
            spare_part.supplier = supplier
            spare_part.supplier_part_number = supplier_part_number
            spare_part.unit = unit
            spare_part.unit_price = unit_price
            spare_part.status = status
            spare_part.min_stock = min_stock
            spare_part.max_stock = max_stock
            spare_part.specifications = specifications
            spare_part.notes = notes
            spare_part.save()
            
            messages.success(request, f'成功更新备件: {spare_part.name}')
            return redirect('spare_parts:sku_management')
            
        except (SparePartCategory.DoesNotExist, Supplier.DoesNotExist, ValueError) as e:
            messages.error(request, '数据验证失败，请检查输入')
        except Exception as e:
            messages.error(request, f'更新备件时发生错误: {str(e)}')
    
    # GET请求显示表单
    categories = SparePartCategory.objects.all()
    suppliers = Supplier.objects.all()
    
    return render(request, 'spare_parts/sku_edit.html', {
        'spare_part': spare_part,
        'categories': categories,
        'suppliers': suppliers,
    })

@login_required
def sku_delete(request, pk):
    """删除SKU"""
    spare_part = get_object_or_404(SparePart, pk=pk)
    
    if request.method == 'POST':
        try:
            part_name = spare_part.name
            spare_part.delete()
            messages.success(request, f'成功删除备件: {part_name}')
        except Exception as e:
            messages.error(request, f'删除备件时发生错误: {str(e)}')
    
    return redirect('spare_parts:sku_management')

@login_required
def sku_detail(request, pk):
    """SKU详情"""
    spare_part = get_object_or_404(SparePart.objects.select_related('category', 'supplier'), pk=pk)
    inventory_records = spare_part.inventory_records.all().order_by('-operation_date')[:50]
    usage_records = spare_part.usage_records.all().order_by('-used_at')[:20]
    
    return render(request, 'spare_parts/sku_detail.html', {
        'spare_part': spare_part,
        'inventory_records': inventory_records,
        'usage_records': usage_records,
    })

# 占位视图函数 - 后续实现
@login_required
def inventory_edit(request, pk):
    messages.info(request, '功能开发中')
    return redirect('spare_parts:inventory_list')

@login_required
def purchase_add(request):
    messages.info(request, '功能开发中')
    return redirect('spare_parts:purchase_list')

@login_required
def purchase_edit(request, pk):
    messages.info(request, '功能开发中')
    return redirect('spare_parts:purchase_list')

@login_required
def purchase_approve(request, pk):
    messages.info(request, '功能开发中')
    return redirect('spare_parts:purchase_list')

@login_required
def purchase_receive(request, pk):
    messages.info(request, '功能开发中')
    return redirect('spare_parts:purchase_list')

@login_required
def supplier_add(request):
    messages.info(request, '功能开发中')
    return redirect('spare_parts:supplier_list')

@login_required
def supplier_edit(request, pk):
    messages.info(request, '功能开发中')
    return redirect('spare_parts:supplier_list')

@login_required
def category_add(request):
    messages.info(request, '功能开发中')
    return redirect('spare_parts:category_list')

@login_required
def category_edit(request, pk):
    messages.info(request, '功能开发中')
    return redirect('spare_parts:category_list')
